"use strict";
const db = uniCloud.database();
const dbCmd = db.command;
const collection = db.collection("outStock");

// 动态选择或创建 Collection 的函数
const getOrCreateCollection = async (tenantId) => {
	const db = uniCloud.database();
	const collectionName = `${tenantId}_sales_report`; // 使用反引号进行字符串插值

	let collection = db.collection(collectionName);

	try {
		// 尝试获取一条数据，检查 Collection 是否存在
		await collection.limit(1).get();
	} catch (error) {
		if (error.message.includes("collection not found")) {
			// 如果 Collection 不存在，创建一个
			await db.createCollection(collectionName);
			console.log(`Collection ${collectionName} 创建成功!`);
		} else {
			// 其他错误直接抛出
			throw error;
		}
	}

	return db.collection(collectionName); // 返回指定 Collection 对象
};

// 新增销售记录
exports.addSalesRecord = async (data) => {
	try {
		if (!data?.user_id) {
			return {
				code: 1,
				message: "新增失败,需要用户！",
				error,
			};
		}
		// 自动计算金额和净利润
		data.amount = data.unit_price * data.quantity;
		data.net_profit = (data.unit_price - data.cost_price) * data.quantity;

		// 设置创建时间
		// data.createTime = Date.now(); // 设置创建时间

		const res = await collection.add(data);
		return {
			code: 0,
			message: "新增成功",
			data: res,
		};
	} catch (error) {
		return {
			code: 1,
			message: "新增失败",
			error,
		};
	}
};


exports.addSalesRecords = async (dataList) => {
	if (!Array.isArray(dataList)) {
		return {
			code: 1,
			message: "新增失败,数据格式错误！",
		};
	} else {
		//开始事务
		const transaction = await db.startTransaction();
		try {
			const promises = dataList.map((item) => {
				return addSalesRecord(item);
			});

			//实现事务
			const res = await Promise.all(promises);
			console.log("res", res);
			if (res.every((item) => item.code === 0)) {
				await transaction.commit();
				return {
					code: 0,
					message: `新增 ${res.length} 条成功`,
				};
			} else {
				await transaction.rollback();
				return {
					code: 1,
					message: "新增失败",
				};
			}
		} catch (e) {
			console.log(e);
			await transaction.rollback();
			return {
				code: 1,
				message: "新增失败",
				error: e,
			};
		}
	}
};

// 新增销售记录（动态选择或创建 Collection）
exports.addTenantSalesRecord = async (tenantId, data) => {
	const collection = await getOrCreateCollection(tenantId); // 获取或创建 Collection

	// 自动计算金额和净利润
	data.amount = data.unit_price * data.quantity;
	data.net_profit = (data.unit_price - data.cost_price) * data.quantity;

	const res = await collection.add(data);
	return {
		code: 0,
		message: "新增成功",
		data: res.id,
	};
};
// 获取销售记录列表（带分页）
exports.getOutSalesRecords = async (page = 1, pageSize = 10, filters = {}) => {
	try {
		// 处理过滤条件
		let enhancedFilter = {
			isDel: 0,
		}; // 基础过滤条件

		// 移除 filters 中的空值、undefined 和 null
		Object.keys(filters).forEach((key) => {
			if (
				filters[key] !== undefined &&
				filters[key] !== null &&
				filters[key] !== ""
			) {
				enhancedFilter[key] = filters[key];
			}
		});

		console.log("查询条件:", enhancedFilter);

		// 构建查询
		const query = collection.where(enhancedFilter);
		const countResult = await query.count();

		// 获取销售记录并进行分页
		const result = await query
			.orderBy("createTime", "desc") // 按创建时间倒序
			.orderBy("status", "asc") // 其次按状态排序
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.get();

		// 打印查询结果，方便调试
		console.log("查询结果:", {
			条件: enhancedFilter,
			总数: countResult.total,
			当前数据: result.data.length,
		});

		return {
			code: 0,
			message: "查询成功",
			data: result.data,
			total: countResult.total,
		};
	} catch (error) {
		console.error("查询出错:", error);
		return {
			code: 1,
			message: "查询失败",
			error: error.message,
		};
	}
};

// 获取销售记录列表（动态选择或创建 Collection）
exports.getTenantSalesRecords = async (
	tenantId,
	page = 1,
	pageSize = 10,
	filter = {}
) => {
	const collection = await getOrCreateCollection(tenantId); // 获取或创建 Collection

	const res = await collection
		.where(filter)
		.skip((page - 1) * pageSize)
		.limit(pageSize)
		.orderBy("status", 1) // 排序：status 为 0 的在前面
		.get();

	return {
		code: 0,
		message: "查询成功",
		data: res.data,
		total: res.affectedDocs, // 总记录数
	};
};

// 根据 ID 获取单条销售记录
exports.getSalesRecordById = async (id) => {
	try {
		// 使用 doc(id).get() 方法根据 ID 获取数据
		const res = await collection.doc(id).get();

		// 如果找到了数据
		if (res.data?.length) {
			return {
				code: 0,
				message: "查询成功",
				data: res.data?.[0],
			};
		} else {
			return {
				code: 1,
				message: "未找到对应的记录",
				data: null,
			};
		}
	} catch (error) {
		return {
			code: 1,
			message: "查询失败",
			error,
		};
	}
};
// 根据多个 ID 获取销售记录
exports.getSalesRecordsByIds = async (ids = []) => {
	try {
		// 如果 ID 数组为空，直接返回空数据
		if (ids.length === 0) {
			return {
				code: 0,
				message: "ID 不能为空",
				data: [],
			};
		}

		// 使用 .where() 和 $in 查询多个 ID 的数据
		const res = await collection
			.where({
				_id: {
					$in: ids,
				}, // 使用 $in 查询多个 ID
			})
			.get();

		// 返回查询结果
		return {
			code: 0,
			message: "查询成功",
			data: res.data,
		};
	} catch (error) {
		return {
			code: 1,
			message: "查询失败",
			error,
		};
	}
};

// 更新销售记录
exports.updateSalesRecord = async (id, data) => {
	console.log(data, "======更新销售记录===updateSalesRecord===========");
	try {
		// 重新计算金额和净利润
		if (data.unit_price && data.quantity) {
			data.amount = data.unit_price * data.quantity;
			data.net_profit = (data.unit_price - data.cost_price) * data.quantity;
		}
		const res = await collection.doc(id).update(data);
		return {
			code: 0,
			message: "更新成功",
			data: res.updated,
		};
	} catch (error) {
		return {
			code: 1,
			message: "更新失败",
			error,
		};
	}
};
// 动态选择Collection
exports.updateTenantSalesRecord = async (tenantId, id, data) => {
	const db = uniCloud.database();
	const collection = db.collection(`${tenantId}_sales_report`); // 动态选择Collection

	if (data.unit_price && data.quantity) {
		data.amount = data.unit_price * data.quantity;
		data.net_profit = (data.unit_price - data.cost_price) * data.quantity;
	}

	const res = await collection.doc(id).update(data);
	return {
		code: 0,
		message: "更新成功",
		data: res.updated,
	};
};

// 删除销售记录
exports.deleteSalesRecord = async (id) => {
	try {
		const res = await collection.doc(id).remove();
		return {
			code: 0,
			message: "删除成功",
			data: res.deleted,
		};
	} catch (error) {
		return {
			code: 1,
			message: "删除失败",
			error,
		};
	}
};
// 动态选择Collection
exports.deleteTenantSalesRecord = async (tenantId, id) => {
	const db = uniCloud.database();
	const collection = db.collection(`${tenantId}_sales_report`); // 动态选择Collection

	const res = await collection.doc(id).remove();
	return {
		code: 0,
		message: "删除成功",
		data: res.deleted,
	};
};

// 出库生成单子并且记录入库出库单
exports.generateStockOutRecord = async (forms, user_id) => {
	const transaction = await db.startTransaction();

	try {
		for (const form of forms) {
			const {
				stock_name,
				product_spec,
				quantity,
				unit_price
			} = form;


			Reflect.deleteProperty(form, 'manufacturers')


			//当前订单未出库数量
			let remainingQuantity = quantity;

			// 新建出库单
			const outStockRes = await transaction.collection("outStock").add({
				...form,
				user_id,
				stock_ids: [],
			});

			// 查找匹配的入库记录
			const inStockList = await transaction
				.collection("inStock")
				.where({
					manufacturer: stock_name, // 商品名称
					specification: product_spec, // 商品规格
					remainingQuantity: dbCmd.gt(0), // 剩余库存大于0
					isInStock: true, //已入库
					userId: user_id, //用户id
					isDel: 0, //未删除
				})
				.orderBy("createTime", "asc") // 先进先出
				.get();

			const stock_ids = [];
			console.log(inStockList, "==========inStockList=====");
			console.log(outStockRes, "==========outStockRes=====");

			for (const inStock of inStockList.data) {
				if (remainingQuantity <= 0) break;
				//当前出库数量
				const deductQty = Math.min(
					remainingQuantity,
					inStock.remainingQuantity
				);
				// 剩余库存数量
				remainingQuantity -= deductQty;

				// 计算利润 = (售价 - 进价) * 出库数量
				const profit = (unit_price - inStock.unitPrice) * deductQty;

				// 更新入库记录
				await transaction
					.collection("inStock")
					.doc(inStock._id)
					.update({
						//剩余库存数量
						remainingQuantity: inStock.remainingQuantity - deductQty,
						outStockRecords: db.command.push({
							id: outStockRes.id,
							quantity: deductQty,
							unitPrice: inStock.unitPrice,
							salePrice: unit_price,
							profit,
							createTime: Date.now(),
						}),
						updateTime: Date.now(),
					});

				//更新出库记录
				await transaction
					.collection("outStock")
					.doc(outStockRes.id)
					.update({
						stock_ids: dbCmd.push({
							id: inStock._id,
							quantity: deductQty,
							unitPrice: inStock.unitPrice,
							salePrice: unit_price,
							profit,
							createTime: Date.now(),
						}),
					});
			}
		}

		// 提交事务
		await transaction.commit();
		return {
			code: 0,
			message: "新增出库单成功",
		};
	} catch (error) {
		// 事务回滚
		await transaction.rollback();
		console.error("出库失败:", error);
		return {
			code: 1,
			message: "新增出库单失败",
			error,
		};
	}
};



// 获取数据库中所有的客户数据 聚合 数量 金额 已付金额（带分页）
exports.getOutStockManagerAggregatedData = async (customer_name, user_id, page = 1, pageSize = 10) => {
	try {
		let matchStage = {
			isDel: 0,
			user_id: user_id,
			status: {
				$nin: [2, 3]
			} // 只统计 status 不等于 2（已付清）和 3（退款）的记录
		};

		if (customer_name) {
			matchStage.customer_name = customer_name;
		}

		// 计算分页的 skip 值
		const skipCount = (page - 1) * pageSize;

		const result = await collection.aggregate()
			.match(matchStage)
			.group({
				_id: '$customer_name', // 分组依据，按客户名称 customer_name 分组
				totalPayableAmount: {
					$sum: '$payable_amount'
				}, // 总应付金额，累加所有订单的 payable_amount
				totalPaidAmount: {
					$sum: '$paid_amount'
				}, // 总已付金额，累加所有订单的 paid_amount
				orderCount: {
					$sum: 1
				}, // 订单数量，统计每个客户的订单总数
				customerPhone: {
					$first: '$customer_phone'
				}, // 客户电话，取该客户的第一条记录中的 customer_phone
				lastOrderDate: {
					$max: '$date'
				}, // 最近订单日期，取该客户所有订单中最晚的 date
				totalQuantity: {
					$sum: '$quantity'
				}, // 总销售数量，累加所有订单的 quantity
				totalNetProfit: {
					$sum: '$net_profit'
				}, // 总净利润，累加所有订单的 net_profit
				vehicleNumbers: {
					$addToSet: '$vehicle_number'
				} // 相关车号列表，收集所有订单的 vehicle_number 并去重
			})
			.project({
				customerName: {
					$ifNull: ['$_id', '未知客户']
				}, // 在 project 阶段处理空值
				totalPayableAmount: 1,
				totalPaidAmount: 1,
				unpaidAmount: {
					$subtract: [{
							$ifNull: ['$totalPayableAmount', 0]
						},
						{
							$ifNull: ['$totalPaidAmount', 0]
						}
					]
				},
				orderCount: 1,
				customerPhone: {
					$ifNull: ['$customerPhone', '']
				},
				lastOrderDate: 1,
				totalQuantity: 1,
				totalNetProfit: 1,
				vehicleNumbers: 1,
				_id: 0
			})
			.sort({
				totalPayableAmount: -1
			}) // 按总应付金额降序排序
			.skip(skipCount) // 跳过前面的记录
			.limit(pageSize) // 限制每页记录数
			.end();

		return {
			success: true,
			data: result?.data || [], // 确保返回空数组而不是 undefined
			message: '数据聚合成功'
		};
	} catch (error) {
		return {
			success: false,
			errorMessage: error.message,
			error: error
		};
	}
};




// 撤销出库单
exports.revertOutStock = async (id, user_id) => {
	const transaction = await db.startTransaction();
	try {
		// 获取出库单
		const outStock = await transaction.collection("outStock").doc(id).get();
		// 获取出库单绑定的入库单
		const inStockList = await transaction
			.collection("inStock")
			.where({
				_id: dbCmd.in(outStock.data.stock_ids.map((item) => item.id)),
			})
			.get();
		console.log(outStock, "===outStock");
		console.log(inStockList, "===inStockList");

		// 遍历入库单，撤销入库
		for (const inStockItem of inStockList.data) {
			// 获取出库单绑定的入库单数量
			const {
				quantity
			} = outStock.data.stock_ids.find(
				(item) => item.id === inStockItem._id
			);

			console.log(inStockItem, "====inStockItem===");
			console.log(quantity, "====quantity===");

			// inStockItem.quantity 

			await transaction
				.collection("inStock")
				.doc(inStockItem._id)
				.update({
					remainingQuantity: inStockItem.remainingQuantity + quantity,
					outStockRecords: inStockItem.outStockRecords.filter(
						(item) => item.id !== id
					),
					updateTime: Date.now(),
				});
		}
		//撤销后，删除出库单
		await transaction.collection("outStock").doc(id).update({
			isDel: 1,
			updateTime: Date.now(),
		});

		// 提交事务
		await transaction.commit();
		return {
			code: 0,
			message: "撤销成功",
		};
	} catch (error) {
		// 事务回滚
		await transaction.rollback();
		console.error("撤销出库失败:", error);
		return {
			code: 1,
			message: "撤销失败",
			error,
		};
	}
};